package com.lixin.web.webSocket.impl;

import com.lixin.constants.ExceptionConstants;
import com.lixin.entity.GroupChatMessage;
import com.lixin.entity.Users;
import com.lixin.exception.LoginFailedException;
import com.lixin.exception.ParamsException;
import com.lixin.exception.TokenRefreshFailedException;
import com.lixin.model.request.RefreshTokenRequest;
import com.lixin.model.response.LoginResponse;
import com.lixin.model.response.Response;
import com.lixin.service.IFriendshipsService;
import com.lixin.service.IGroupInfoService;
import com.lixin.service.IUsersService;
import com.lixin.web.jwt.JwtConstants;
import com.lixin.web.jwt.JwtService;
import com.lixin.web.jwt.JwtUtils;
import com.lixin.web.jwt.TokenStorage;
import com.lixin.web.netty.NettyServerStarter;
import com.lixin.web.netty.NettyUtil;
import com.lixin.web.netty.UserSessionManager;
import com.lixin.web.webSocket.SystemManager;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * Description:
 * Copyright:   Copyright (c)2023
 * Company:     sci
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2023-08-02 22:12:02
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2023-08-02     张李鑫                     1.0         1.0 Version
 */
@Component("system")
public class SystemManagerImpl implements SystemManager {

    @Autowired
    private IUsersService iUsersService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private TokenStorage tokenStorage;

    @Autowired
    private UserSessionManager userSessionManager;

    @Override
    public Response<LoginResponse> login(Users users) {
        Users user = iUsersService.login(users);
        if (user != null) {
            //登录成功创建token
            return Response.success(createTokenAndSaveToTokenStorageAndUserSessionManager(user.getUserId()));
        }
        throw new LoginFailedException(ExceptionConstants.LOGIN_FAILED);
    }

    @Override
    public Response<LoginResponse> refreshToken(RefreshTokenRequest refreshToken) {
        String token = refreshToken.getRefreshToken();
        Integer userId = jwtUtils.getUserIdByToken(token);
        if (jwtService.validateRefreshToken(token,userId)) {
            return Response.success(new LoginResponse(jwtService.refreshToken(userId)));
        }
        throw new TokenRefreshFailedException(ExceptionConstants.TOKEN_REFRESH_FAILED);
    }


    /**
     * 创建token并存储设置channel userId
     *
     * @param userId
     * @return
     */
    private LoginResponse createTokenAndSaveToTokenStorageAndUserSessionManager(Integer userId) {
        String accessToken = jwtUtils.createToken(userId);
        String refreshToken = jwtUtils.createToken(userId, JwtConstants.REFRESH_TOKEN_EXPIRATION_TIME);
        tokenStorage.storeTokens(userId, accessToken, refreshToken);
        Channel channel = NettyServerStarter.ctxThreadLocal.get().channel();
        NettyUtil.setAttr(channel, NettyUtil.UID, userId);
        userSessionManager.addUserSession(userId, channel);
        return new LoginResponse(accessToken, refreshToken);
    }

//    public List<Message> getUnreadMessages(Integer userId) {
//        List<Message> unreadMessages = new ArrayList<>();
//
//        // 根据用户ID查询未读消息
//        List<Message> allMessages = messageService.getAllMessagesForUser(userId);
//
//        // 过滤出未读消息
//        for (Message message : allMessages) {
//            if (!message.isRead()) {
//                unreadMessages.add(message);
//            }
//        }
//
//        return unreadMessages;
//    }



}
